<?php
/**
 *产品调拨申请控制器
 *@author shipanpan
 */
class Backup_TransferApplyController extends Controller_NeedLogin {

	public function listAction() {
		$stockTransferApplyModel = new Backup_Model_StockTransferApply();

		$queryParameter = $this->getRequest()->getQuery();
		$fromWarehouse = $queryParameter['from_warehouse'] ?? '';
		$toWarehouse = $queryParameter['to_warehouse'] ?? '';

		//默认获取 电子仓=>分销仓 的调拨申请
		if (!($fromWarehouse && $toWarehouse)) {
			$fromWarehouse = "DZWH";
			$toWarehouse = "YB";
		}
		$this->db = Model_Db::getInstance();

		$querySql = "select %fields% from b_stock_transfer_apply as transfer_apply
                     left join b_story_transfer_log as transfer_log on transfer_apply.id=transfer_log.stock_transfer_apply_id
		             left join p_product  as product on transfer_apply.goods_sn=product.goods_sn
		             left join p_product_purchase as product_purchase on transfer_apply.goods_sn=product_purchase.goods_sn
                     left join p_product_warehouse_stock as stock on stock.goods_sn=transfer_apply.goods_sn and stock.warehouse_code=transfer_apply.from_warehouse
		             where product.goods_sn is not null";

		$where = " AND " . $this->db->quoteInto("transfer_apply.from_warehouse=?", $fromWarehouse) . " ";
		$where .= "AND " . $this->db->quoteInto("transfer_apply.to_warehouse=?", $toWarehouse) . " ";

		//产品类别查询
		if ($queryParameter['product_category'] ?? "") {
			$productCatalogModel = new Application_Model_ProductCatalog();
			$allChildCatalogId = $productCatalogModel->getAllChildCatalog($queryParameter['product_category'], ['id']);
			$allChildCatalogId = array_column($allChildCatalogId, 'id');
			$where .= "AND " . $this->db->quoteInto("product.catalog_id in(?)", $allChildCatalogId) . " ";
		}

		//搜索关键字
		if ($queryParameter['goods_sn'] ?? "") {
			$where .= "AND " . $this->db->quoteInto("transfer_apply.goods_sn in (?)", explode(',', $queryParameter['goods_sn'])) . " ";
		}

		//申请审核状态
		if ($queryParameter['apply_status'] ?? "") {
			$where .= "AND " . $this->db->quoteInto("transfer_apply.status =?", $queryParameter['apply_status']) . " ";
		}

		//调拨申请时间
		if ($queryParameter['min_apply_date'] ?? "") {
			list($year, $month, $day) = explode('-', $queryParameter['min_apply_date']);
			if (checkdate($month, $day, $year)) {
				$where .= "AND " . $this->db->quoteInto("transfer_apply.create_date >=?", $queryParameter['min_apply_date']) . " ";
			}
		}
		if ($queryParameter['max_apply_date'] ?? "") {
			list($year, $month, $day) = explode('-', $queryParameter['max_apply_date']);
			if (checkdate($month, $day, $year)) {
				$where .= "AND " . $this->db->quoteInto("transfer_apply.create_date <=?", $queryParameter['max_apply_date']) . " ";
			}
		}

		//调拨数量查询
		if (($queryParameter['apply_quantity_operator'] ?? "") && ($queryParameter['apply_quantity']) && $queryParameter['apply_quantity']) {
			$quantityOperator = (int) $queryParameter['apply_quantity_operator'];
			if (in_array($quantityOperator, [1, 2])) {
				$operator = $quantityOperator == 1 ? ">=" : "<";
				$queryParameter['apply_quantity'] = (int) $queryParameter['apply_quantity'];
				$where .= "AND " . $this->db->quoteInto("transfer_apply.apply_quantity $operator ?", $queryParameter['apply_quantity']) . " ";
			}
		}

		if ($where) {
			$querySql .= " " . $where;
		}

		$countQuerySql = str_replace("%fields%", "count(*)", $querySql);
		$allAmount = $this->db->fetchOne($countQuerySql);

		$transferApplyList = [];
		$pageLink = "";
		if ($allAmount) {
			$queryField = "transfer_apply.*,transfer_log.*,product.thumb_url,product.product_name,product.product_status,stock.last_storage_time,product_purchase.purchaser,stock.base_stock,stock.stock_can_allot,stock.stock_on_way,stock.stock_wait_for_send";
			$querySql = str_replace("%fields%", $queryField, $querySql);
			$page = (int) ($this->getRequest()->getParam('page') ?? 1);
			$pageLength = (int) $this->page_size;

			$limitSql = " limit " . ($page - 1) * $pageLength . "," . $pageLength;
			$querySql .= $limitSql;
			$transferApplyList = $this->db->fetchAll($querySql);
			$pageLink = $this->page($allAmount, $pageLength);
		}

		if (!empty($transferApplyList)) {
			$productSalesCommonModel = new Application_Model_ProductSales();
			foreach ($transferApplyList as &$oneTransferApply) {
				//获取查询结果商品的销量信息
				$productSalesInfo = $productSalesCommonModel->getOne($oneTransferApply['goods_sn'], $oneTransferApply['from_warehouse']);
				$productSalesInfo = (array) $productSalesInfo;
		
				$oneTransferApply['the7DaySales'] = $productSalesInfo['real_sale_7'] ?? 0;
				$oneTransferApply['the15DaySales'] = $productSalesInfo['real_sale_15'] ?? 0;
				$oneTransferApply['the30DaySales'] = $productSalesInfo['real_sale_30'] ?? 0;
				//可用库存
				$oneTransferApply['availableStock'] = $oneTransferApply['base_stock'];

				//上一次审核结果
				$lastCheckResult = $stockTransferApplyModel->getProductLastApplyCheckResult($oneTransferApply['goods_sn'], $oneTransferApply['from_warehouse'], $oneTransferApply['to_warehouse'], $oneTransferApply['create_date']);
				$oneTransferApply['lastCheckResult'] = ($lastCheckResult === false) ? "" : $lastCheckResult;
			}

		}

		$transferApply = [
			'status' => Backup_Model_StockTransferApply::STATUS,
			'productStatus' => Application_Model_Product::STATUS,
		];

		$autoCheckRuleModel = new Backup_Model_TransferApplyAutoCheckRule();
		$autoCheckRule = $autoCheckRuleModel->getOneDetail($fromWarehouse, $toWarehouse);
		$autoCheckLifeCycleRule = [];
		if ($autoCheckRule) {
			$allAutoCheckRule = [];
			foreach ($autoCheckRule as $oneRule) {
				$conditionType = $oneRule['condition_type'];
				$allAutoCheckRule[$conditionType][] = $oneRule;
			}
			if (isset($allAutoCheckRule['lifeCycle'])) {
				$autoCheckLifeCycleRule = $allAutoCheckRule['lifeCycle'];
				$autoCheckLifeCycleRule = array_column($autoCheckLifeCycleRule, null, 'condition_eq_value');
			}
		}

		//获取分类的父级信息，用于设置查询页面类别筛选条件选择框
		$queryParameter['catalogPath'] = '';
		if (isset($queryParameter['product_category']) && $queryParameter['product_category']) {
			$ProductCatalogModel = new Application_Model_ProductCatalog();
			$catalogPath = $ProductCatalogModel->getDetailById($queryParameter['product_category'], ['path']);
			$queryParameter['catalogPath'] = $catalogPath['path'] ?? "";
			$queryParameter['catalogPath'] = ltrim($queryParameter['catalogPath'], "0,");
		}

		$menuApi = new Application_Model_Privilege();
		$breads = $menuApi->getBreads($this->module, $this->controller, $this->action . '?from_warehouse=' . $fromWarehouse . '&to_warehouse=' . $toWarehouse);
		$this->smarty->assign('bread', $breads);

		$warehose_model = new Application_Model_Warehouse();
		$this->smarty->assign('fromWarehouseName', $warehose_model->getName($fromWarehouse));
		$this->smarty->assign('toWarehouseName', $warehose_model->getName($toWarehouse));

		$this->smarty->assign('fromWarehouse', $fromWarehouse);
		$this->smarty->assign('queryParameter', $queryParameter);
		$this->smarty->assign('toWarehouse', $toWarehouse);
		$this->smarty->assign('autoCheckLifeCycleRule', $autoCheckLifeCycleRule);
		$this->smarty->assign('page_link', $pageLink);
		$this->smarty->assign('transferApply', $transferApply);
		$this->smarty->assign('applyList', $transferApplyList);
		$this->smarty->assign('pdmDomain', Helper_Config::get('url', 'pdm', 'url'));
		$this->smarty->display('transferApplyList.tpl');
	}

	/**
	 * 审核通过调拨申请
	 * @return [type] [description]
	 */
	public function agreeAction() {
		$applyIdStr = $this->getRequest()->getPost('applyId');
		$agreeApplyId = explode(",", $applyIdStr);
		$stockTransferApplyModel = new Backup_Model_StockTransferApply();

		foreach ($agreeApplyId as $oneAppleId) {
			$oneAppleId = (int) (trim($oneAppleId));
			$agreeResult = $stockTransferApplyModel->agreeByAdmin($oneAppleId);
			if ($agreeResult === false) {
				echo json_encode(['status' => false, 'msg' => "id为" . $oneAppleId . "的调拨申请审核通过操作失败，原因:" . $stockTransferApplyModel->getErrorMsg()]);
				exit;
			}
		}
		echo json_encode(['status' => true, 'msg' => '审核通过操作成功！']);
	}

	/**
	 * 驳回调拨申请
	 * @return [type] [description]
	 */
	public function rejectAction() {
		$rejectApplyIdStr = $this->getRequest()->getPost('applyId');
		$rejectApplyId = explode(",", $rejectApplyIdStr);

		$stockTransferApplyModel = new Backup_Model_StockTransferApply();

		foreach ($rejectApplyId as $oneAppleId) {
			$oneAppleId = (int) (trim($oneAppleId));
			$rejectResult = $stockTransferApplyModel->rejectByAdmin($oneAppleId);
			if ($rejectResult === false) {
				echo json_encode(['status' => false, 'msg' => "id为" . $oneAppleId . "的调拨申请驳回操作失败，原因:" . $stockTransferApplyModel->getErrorMsg()]);
				exit;
			}
		}
		echo json_encode(['status' => true, 'msg' => '驳回操作成功！']);
	}

	/**
	 * 保存各仓库的系统自动审核调拨申请规则
	 * @return [type] [description]
	 */
	public function saveCheckRuleAction() {
		$transterFromWarehouse = $this->getRequest()->getPost('from_warehouse');
		$transferToWarehouse = $this->getRequest()->getPost('to_warehouse');

		$ruleTypeArr = $this->getRequest()->getPost('condition_type');
		$operatorArr = $this->getRequest()->getPost('condition_operator');
		$minValueArr = $this->getRequest()->getPost('condition_min_value');
		$maxValueArr = $this->getRequest()->getPost('condition_max_value');
		$eqValueArr = $this->getRequest()->getPost('condition_eq_value');
		$ruleLowerQuantityArr = $this->getRequest()->getPost('check_quantity_lower');
		$ruleUpperQuantityArr = $this->getRequest()->getPost('check_quantity_upper');

		$ruleItem = [];
		foreach ($ruleTypeArr as $index => $ruleType) {
			$item['condition_type'] = $ruleType;
			$item['condition_operator'] = $operatorArr[$index];
			$item['condition_min_value'] = $minValueArr[$index];
			$item['condition_max_value'] = $maxValueArr[$index];
			$item['condition_eq_value'] = $eqValueArr[$index];
			$item['check_quantity_lower'] = $ruleLowerQuantityArr[$index];
			$item['check_quantity_upper'] = $ruleUpperQuantityArr[$index];

			$ruleItem[] = $item;
		}

		$applyAutoCheckRuleModel = new Backup_Model_TransferApplyAutoCheckRule();

		$saveSuccess = $applyAutoCheckRuleModel->save($transterFromWarehouse, $transferToWarehouse, $ruleItem);
		if ($saveSuccess) {
			$this->_helper->json(['success' => true, 'msg' => '保存成功！']);
		} else {
			$this->_helper->json(['success' => false, 'msg' => $applyAutoCheckRuleModel->getErrorMsg()]);
		}

	}
}